package com.rainbow.redis.plus.core.starter;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import com.rainbow.qps.FlowHelper;
import com.rainbow.qps.FlowType;
import com.rainbow.redis.plus.core.constant.RedisConstant;
import com.rainbow.redis.plus.core.metrics.RedisPlusMetrics;
import com.rainbow.redis.plus.core.monitor.BlackTagService;
import com.rainbow.redis.plus.core.receiver.RedisReceiver;

@Configuration
@ConditionalOnProperty(name = RedisConstant.REDIS_MINOTOR_ENABLED,havingValue = "true")
@AutoConfigureAfter({RedisPlusAutoConfiguration.class,ApplicationContextConfigAutoConfiguration.class})
public class MonitorConfigAutoConfiguration implements EnvironmentAware {
	
	private Environment environment;
	
	@Bean
    public BlackTagService blackTagService() {
        return new BlackTagService();
    }
	
	@Bean
    public RedisPlusMetrics redisPlusMetrics() {
    	return new RedisPlusMetrics();
    }
    
    @Bean
    public FlowHelper flowHelper() {
    	return new FlowHelper(FlowType.Second,FlowType.Minute,FlowType.Hour);
    }
    
    @Bean
    public RedisReceiver redisReceiver() {
    	return new RedisReceiver();
    }
    
    /**
     * 消息监听器适配器，绑定消息处理器，利用反射技术调用消息处理器的业务方法
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(RedisReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
    
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 可以添加多个 messageListener，配置不同的交换机
        String topic = environment.getProperty(RedisConstant.REDIS_PATTERN_TOPIC, String.class, "channel:project:black");
        container.addMessageListener(listenerAdapter, new PatternTopic(topic));

        return container;
    }

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}
}
